package com.example;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TabHost;

public class Start extends TabActivity {
	static final String TAG = "Start";
	private SharedPreferences prefs;
	private final static String CONSUMER_KEY = "i6hchEkpicnjWlwoqyw";
	private final static String CONSUMER_SECRET = "yD4vxgT21yFsgMQS50Qabwvx3kIR70NhlpSa8ImI";
	private final static String USER_KEY = "27429414-CHAtID7NmAmF7UCH2F8M9ffvNlOrdZjOqyfOrfq0H";
	private final static String USER_SECRET = "YfRgfWmrqSbjAtyUIzQCHZo5WcPMLQj0mQOqPjRyo";
	
	private CommonsHttpOAuthConsumer httpOauthConsumer;
	private OAuthProvider httpOauthprovider;
	private final String CALLBACKURL = "socialclient://startactivity";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		prefs
				.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
					public void onSharedPreferenceChanged(
							SharedPreferences arg0, String arg1) {
						// twitter = null;
					}
				});
		setProxySettings();
		if(USER_KEY==null || USER_SECRET==null){
		httpOauthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
				CONSUMER_SECRET);
		httpOauthprovider = new DefaultOAuthProvider(
				"http://twitter.com/oauth/request_token",
				"http://twitter.com/oauth/access_token",
				"http://twitter.com/oauth/authorize");
		String authUrl = null;
		try {
			authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer,
					CALLBACKURL);
		} catch (OAuthMessageSignerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
		} else {
			setupTabs();
		}
	}

	private void setupTabs() {
		new Thread(new Runnable() {
			public void run() {
				startService(new Intent(getApplicationContext(),
						UpdaterService.class));
			}
		});
		setContentView(R.layout.start);

		TabHost tabHost = getTabHost(); // The activity TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent tempIntent; // Reusable Intent for each tab

		// Create an Intent to launch an Activity for the tab (to be
		// reused)
		tempIntent = new Intent().setClass(this, MyTwitter.class);

		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost.newTabSpec("update")
				.setIndicator("Update", null).setContent(tempIntent);
		tabHost.addTab(spec);

		// Do the same for the other tabs
		tempIntent = new Intent().setClass(this, Timeline.class);
		spec = tabHost.newTabSpec("timeline").setIndicator("Timeline",
				null).setContent(tempIntent);
		tabHost.addTab(spec);

		// Do the same for the other tabs
		tempIntent = new Intent().setClass(this, ListTimeline.class);
		spec = tabHost.newTabSpec("lists").setIndicator("Lists", null)
				.setContent(tempIntent);
		tabHost.addTab(spec);

		tempIntent = new Intent().setClass(this, Prefs.class);
		spec = tabHost.newTabSpec("prefs").setIndicator("Prefs", null)
				.setContent(tempIntent);
		tabHost.addTab(spec);

		int childCount = tabHost.getTabWidget().getChildCount();
		for (int i = 0; childCount > i; i++)
			tabHost.getTabWidget().getChildAt(i).setLayoutParams(
					new LinearLayout.LayoutParams(85, 37));
		tabHost.setCurrentTabByTag("update");
		Log.d(TAG, "onReceive started ListService");
		
	}

	@Override
	public void onResume() {
		super.onResume();
		// Cancel notification
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager
				.cancel(UpdaterService.Updater.STATUS_NOTIFICATION_ID);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopService(new Intent(getApplicationContext(), UpdaterService.class));
	}

	public void setProxySettings() {
		if (prefs.getBoolean("proxy", false)) {
			System.setProperty("http.proxyHost", prefs.getString("proxyServer",
					""));
			System.setProperty("http.proxyPort", prefs.getString("proxyPort",
					""));
			System.setProperty("http.proxyUser", prefs.getString(
					"proxyUserName", ""));
			System.setProperty("http.proxyPassword", prefs.getString(
					"proxyPassword", ""));
		} else {
			System.setProperty("http.proxyHost", "");
			System.setProperty("http.proxyPort", "");
			System.setProperty("http.proxyUser", "");
			System.setProperty("http.proxyPassword", "");

		}
	}

	/**
	 * After use authorizes this is the function where we get back callbac with
	 * user specific token and secret token. You might want to store this token
	 * for future use.
	 */
	@Override
	protected void onNewIntent(Intent intent) {

		super.onNewIntent(intent);

		Uri uri = intent.getData();
		// Check if you got NewIntent event due to Twitter Call back only
		if (uri != null && uri.toString().startsWith(CALLBACKURL)) {

			String verifier = uri
					.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);

			try {
				// this will populate token and token_secret in consumer
				httpOauthprovider.retrieveAccessToken(httpOauthConsumer,
						verifier);
				String userKey = httpOauthConsumer.getToken();
				String userSecret = httpOauthConsumer.getTokenSecret();
				//client.setAuthorizationCode("123");
				// Optional: store the authorisation token details
  				setupTabs();
			} catch (Exception e) {
				Log.d("", e.getMessage());
			}

		}
	}

}
